<template>
  <el-dialog
    center
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
  >
    <span>
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
        label-position="left"
        center
      >
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :data="uploadObj"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="图形码" prop="code">
              <el-input v-model="form.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7" style="margin-left:15px;">
            <img
              :src="smsCaptchaUrl"
              alt=""
              @click="btnSrc"
              style="width:100%;height:40px;"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="验证码" prop="rcode">
              <el-input v-model="form.rcode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7" style="margin-left:20px;">
            <el-button @click="getVcode">获取用户验证码</el-button>
          </el-col>
        </el-row>
      </el-form>
    </span>
    <span slot="footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'register',
  data () {
    return {
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads',
      uploadObj: {},
      imageUrl: '',
      smsCaptchaUrl: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      dialogVisible: false,
      form: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        code: '', // 图形码
        rcode: '' // 验证码
      },
      rules: {
        username: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // rule 规则，基本用不到
              // value 就是你输入的值
              // callback 回到，失败： callback(new Error('错误信息')) 成功：callback，注意：无论成功失败都要调用
              if (!value) {
                callback(new Error('邮箱不能为空'))
                return
              }
              // 在下一行禁用eslint，类似上一种方法，只是写的位置不同罢了
              //   eslint-disable-next-line
              const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (!reg.test(value)) {
                callback(new Error('邮箱不合法'))
                return
              }

              // 不要忘记我
              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // rule  校验规则
              // value  输入的值
              // callback 回调函数  带参数的callback返回错误信息    不带参数callback是正确
              if (!value) {
                callback(new Error('手机号码不能为空'))
                return
              }
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                callback(new Error('请输入正确的手机格式'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6-16位', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证不能为空', trigger: 'blur' },
          { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
        ],
        rcode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
        avatar: [{ required: true, message: '头像不能为空', trigger: 'change' }]
      }
    }
  },
  watch: {
    dialogVisible (newValue) {
      if (!newValue) {
        // 调用表单的清空方法（把校验也清空）
        this.$refs.form.resetFields()

        //清空预览的图片
        this.imageUrl = ''
      }
    }
  },
  methods: {
    btnSrc () {
      this.smsCaptchaUrl =
        process.env.VUE_APP_BASEURL + '/captcha?type=login&r=' + Date.now()
    },
    // 获取验证码
    async getVcode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })

      if (num === 2) {
        const res = await this.$axios.post('/sendsms', {
          phone: this.form.phone,
          code: this.form.code
        })

        if (res.code === 200) {
          this.form.rcode = res.data.captcha
        } else {
          this.$message({
            type: 'error',
            message: res.message,
            duration: 1000
          })

          // 刷新图形码
          this.btnSrc()
        }
      }
    },
    handleAvatarSuccess (res, file) {
      if (res.code === 200) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.form.avatar = res.data.file_path
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 1000
        })
      }
    },
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.uploadObj.image = file
      return isImage && isLt2M
    },
    submit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return

        const res = await this.$axios.post('/register', this.form)

        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '注册成功',
            duration: 1000
          })
          this.dialogVisible = false
        } else {
          // 提示
          this.$message({
            type: 'error',
            message: res.message,
            duration: 1000
          })
          // 刷新图形码
          this.btnSrc()
        }
      })
    }
  }
}
</script>

<style>
.avatar-uploader {
  text-align: center;
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
